package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/admin.html","/insertProduct.html"})
public class MyFilter implements Filter {
    //初始化是执行的方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //销毁是执行的方法
    @Override
    public void destroy() {

    }

    //此方法是请求到服务器之前和之后都会调用的方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器工作了");
        HttpServletRequest re = (HttpServletRequest) servletRequest;
        HttpServletResponse sp = (HttpServletResponse) servletResponse;
        //取出请求对象里会话对象
        HttpSession session = re.getSession();
        //取出session里的用户对象
        User user = (User) session.getAttribute("user");
        //判断是否登录
        if (user != null) {
            filterChain.doFilter(servletRequest,servletResponse);//此代码代表放行
        }else {
            //未登录的情况下让客户端重定向到登录页面
            sp.sendRedirect("/login.html");
        }
    }
}
